import {createRouter, createWebHashHistory} from 'vue-router'
// import { routes } from './router.config'
import { routes } from './routers'
import { nextTick } from 'vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user';
import { menuList } from '@/router/menulist'
import SmartLayout from '@/views/layout/layout.vue';
// import { clearAllCoolies, getTokenFromCookie } from '@/utils/cookie-util';
// import { localClear } from '@/utils/local-util';
NProgress.configure({easing: 'ease',speed: 500,showSpinner: false,trickleSpeed: 200,minimum: 0.3})
export const router = createRouter({
  history: createWebHashHistory('/backend'),
  routes,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
});
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (to.path === '/404' || to.path === '/login') {
    next();
    return;
  }
  // 验证登录
//   const token = getTokenFromCookie();
//   if (!token) {
//     clearAllCoolies();
//     localClear();
//     next({ path: '/login' });
//     return;
//   }

  // 首页
  if (to.path == '/home') {
    next();
    useUserStore().setTagNav(to, from);
    return;
  }
  useUserStore().setTagNav(to, from);
  if (to.meta.keepAlive) {
    nextTick(() => {
      useUserStore().pushKeepAliveIncludes(to.name?.toString());
    });
  }
  next()
});

router.afterEach(() => {
  NProgress.done();
});

export function buildRoutes(menuRouterList:any) {

  console.log('menuRouterList',menuRouterList)
  const routerList = [];
  // 获取所有vue组件引用地址 用于构建路由
  const modules = import.meta.glob('../views/**/**.vue');

  for (const e of menuList) {
    if (!e.menuId) {
      continue;
    }
    if (!e.path) {
      continue;
    }
    let route = {
      path: e.path.startsWith('/') ? e.path : `/${e.path}`,
      // 使用【menuId】作为name唯一标识
      name: e.menuId.toString(),
      meta: {
        // 数据库菜单(页面)id
        id: e.menuId.toString(),
        // 组件名称
        componentName: e.menuId.toString(),
        // 菜单展示
        title: e.menuName,
        // 菜单图标展示
        icon: e.icon,
        // 是否在菜单隐藏
        hideInMenu: !e.visibleFlag,
        // 页面是否keep-alive缓存
        keepAlive: e.cacheFlag
      }
    }
    let componentPath = e.component && e.component.startsWith('/') ? e.component : '/' + e.component;
    let relativePath = `../views${componentPath}`;
    // @ts-ignore
    route.component = modules[relativePath];
    routerList.push(route);
  }
  router.addRoute({
    path: '/',
    meta: {},
    component: SmartLayout,
    // @ts-ignore
    children: routerList,
  });
}
